using UnityEngine;
using System.Collections.Generic;
using UndergroundSurvival.Rooms;

namespace UndergroundSurvival.Managers
{
    public class ResourceTransportManager : MonoBehaviour
    {
        public static ResourceTransportManager Instance { get; private set; }

        [Header("Transport Settings")]
        private float transportInterval = 1f;
        private float maxTransportDistance = 10f;
        private float transportSpeed = 5f;

        private Dictionary<string, List<Room>> resourceProducers = new Dictionary<string, List<Room>>();
        private Dictionary<string, List<Room>> resourceConsumers = new Dictionary<string, List<Room>>();
        private float transportTimer = 0f;

        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
            }
            else
            {
                Destroy(gameObject);
            }
        }

        private void Update()
        {
            transportTimer += Time.deltaTime;
            if (transportTimer >= transportInterval)
            {
                ProcessResourceTransport();
                transportTimer = 0f;
            }
        }

        public void SetTransportInterval(float interval)
        {
            transportInterval = interval;
        }

        public void SetMaxTransportDistance(float distance)
        {
            maxTransportDistance = distance;
        }

        public void SetTransportSpeed(float speed)
        {
            transportSpeed = speed;
        }

        public void RegisterRoom(Room room)
        {
            if (room is BaseRoom baseRoom)
            {
                // 注册生产者
                if (baseRoom.productionOutputs != null)
                {
                    foreach (var output in baseRoom.productionOutputs)
                    {
                        if (!resourceProducers.ContainsKey(output.resourceName))
                        {
                            resourceProducers[output.resourceName] = new List<Room>();
                        }
                        resourceProducers[output.resourceName].Add(room);
                    }
                }

                // 注册消费者
                if (baseRoom.consumptionInputs != null)
                {
                    foreach (var input in baseRoom.consumptionInputs)
                    {
                        if (!resourceConsumers.ContainsKey(input.resourceName))
                        {
                            resourceConsumers[input.resourceName] = new List<Room>();
                        }
                        resourceConsumers[input.resourceName].Add(room);
                    }
                }
            }
        }

        public void UnregisterRoom(Room room)
        {
            if (room is BaseRoom baseRoom)
            {
                // 注销生产者
                if (baseRoom.productionOutputs != null)
                {
                    foreach (var output in baseRoom.productionOutputs)
                    {
                        if (resourceProducers.ContainsKey(output.resourceName))
                        {
                            resourceProducers[output.resourceName].Remove(room);
                        }
                    }
                }

                // 注销消费者
                if (baseRoom.consumptionInputs != null)
                {
                    foreach (var input in baseRoom.consumptionInputs)
                    {
                        if (resourceConsumers.ContainsKey(input.resourceName))
                        {
                            resourceConsumers[input.resourceName].Remove(room);
                        }
                    }
                }
            }
        }

        private void ProcessResourceTransport()
        {
            foreach (var resourceType in resourceProducers.Keys)
            {
                if (!resourceConsumers.ContainsKey(resourceType)) continue;

                var producers = resourceProducers[resourceType];
                var consumers = resourceConsumers[resourceType];

                foreach (var producer in producers)
                {
                    if (!producer.isBuilt || !producer.isFunctioning) continue;

                    var baseProducer = producer as BaseRoom;
                    if (baseProducer == null) continue;

                    foreach (var output in baseProducer.productionOutputs)
                    {
                        if (output.resourceName != resourceType) continue;

                        // 找到最近的消费者
                        Room nearestConsumer = FindNearestConsumer(producer, consumers, resourceType);
                        if (nearestConsumer != null)
                        {
                            // 传输资源
                            TransportResource(producer, nearestConsumer, resourceType, output.amount);
                        }
                    }
                }
            }
        }

        private Room FindNearestConsumer(Room producer, List<Room> consumers, string resourceType)
        {
            Room nearest = null;
            float minDistance = float.MaxValue;

            foreach (var consumer in consumers)
            {
                if (!consumer.isBuilt || !consumer.isFunctioning) continue;

                float distance = Vector3.Distance(producer.transform.position, consumer.transform.position);
                if (distance <= maxTransportDistance && distance < minDistance)
                {
                    var baseConsumer = consumer as BaseRoom;
                    if (baseConsumer != null && baseConsumer.consumptionInputs != null)
                    {
                        foreach (var input in baseConsumer.consumptionInputs)
                        {
                            if (input.resourceName == resourceType)
                            {
                                nearest = consumer;
                                minDistance = distance;
                                break;
                            }
                        }
                    }
                }
            }

            return nearest;
        }

        private void TransportResource(Room producer, Room consumer, string resourceType, float amount)
        {
            var baseProducer = producer as BaseRoom;
            var baseConsumer = consumer as BaseRoom;

            if (baseProducer == null || baseConsumer == null) return;

            // 检查生产者是否有足够的资源
            if (!ResourceManager.Instance.HasEnoughResource(resourceType, amount))
                return;

            // 检查消费者是否需要该资源
            bool needsResource = false;
            foreach (var input in baseConsumer.consumptionInputs)
            {
                if (input.resourceName == resourceType)
                {
                    needsResource = true;
                    break;
                }
            }

            if (!needsResource) return;

            // 执行资源传输
            ResourceManager.Instance.ModifyResource(resourceType, -amount);
            ResourceManager.Instance.ModifyResource(resourceType, amount);

            // 创建传输效果
            CreateTransportEffect(producer.transform.position, consumer.transform.position);
        }

        private void CreateTransportEffect(Vector3 start, Vector3 end)
        {
            // TODO: 实现资源传输的视觉效果
            // 可以使用粒子系统或简单的线条来表示资源流动
        }
    }
} 